package collection;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;

public class NullCollectionForEach {
    @SuppressWarnings({ "null", "unused" })
    @Test(expected = NullPointerException.class)
    public void testNullListForEach() {
        List<Integer> nullList = null;

        // there would have a NullPointerException when this loop begin
        for (Integer i : nullList) {
        }
    }

    @SuppressWarnings("null")
    @Test(expected = NullPointerException.class)
    public void testNullListIteratorForEach() {
        List<Integer> nullList = null;
        for (Iterator<Integer> i = nullList.iterator(); i.hasNext();) {
            i.next();
        }
    }

    @SuppressWarnings("unused")
    @Test
    public void testSafeNullListForEach() {
        List<Integer> nullList = null;

        int loopCount = 0;
        for (Integer i : safeList(nullList)) {
            loopCount++;
        }
        
        Assert.assertEquals(0, loopCount);
    }

    @SuppressWarnings("unchecked")
    private <T> List<T> safeList(List<T> l) {
        return l != null ? l : Collections.EMPTY_LIST;
    }
    // public static void main(String[] args) {

    // there would have a NullPointerException in this spe
    // for (Integer i : nullList)
    // {
    // System.out.println(i);
    // }
    // nullList = new ArrayList<Integer>();
    // nullList.add(2);
    // nullList.add(4);
    // nullList.add(6);
    // nullList.add(3);
    //
    // for (Iterator<Integer> i = nullList.iterator(); i.hasNext();)
    // {
    // Integer next = i.next();
    // if (next.equals(4))
    // {
    // i.remove();
    // }
    // }
    //
    // System.out.println("List size: " + nullList.size());
    // for (Integer i : nullList)
    // {
    // System.out.println(i);
    // }
    // }
}
